#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Time      :2019/4/10
# @Author    :breeze
# @Email     :wangbaoshan@bbdservice.com
# @File      :IC02_GuaranBalPro
# @Software  :PyCharm


'''eof
name:对外担保余额占比
code:IC02_GuaranBalPro_2D
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import sys
import re
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def floatCheck(str):
    try:
        float(str)
        return True
    except:
        return False


def guaranBalPro():
    data = IC_DSJ_2D.get('data')
    factor = []
    factor2 = []
    # 信贷交易信息概要 PCO[1.1,0]
    PCO = getTable(data, 'PCO', 1, 0)
    if PCO == [{}]:
        return u'缺失值'
    elif PCO == 0:
        return 0
    else:
        # 信贷交易信息概要信息单元 PC02[0.1,0]
        PC02 = getTable(PCO[0], 'PC02', 0, 0)
        if PC02 == [{}]:
            return u'缺失值'
        elif PC02 == 0:
            return 0
        else:
            # 相关还款责任汇总信息段 PC02K[0.1,1]
            PC02K = getTable(PC02[0], 'PC02K', 0, 1)
            if PC02K == [{}]:
                return u'缺失值'
            elif PC02K == 0:
                return 0
            else:
                # 相关还款责任汇总信息 PC02KH[1.4,1]
                PC02KH = getTable(PC02K[0], 'PC02KH', 1, 1)
                if PC02KH == [{}]:
                    return u'缺失值'
                elif PC02KH == 0:
                    return 0
                else:
                    if len(PC02KH) > 0:
                        for i in PC02KH:
                            # 还款责任类型
                            PC02KD02 = i.get("PC02KD02")
                            # 余额
                            PC02KJ02 = i.get("PC02KJ02")
                            # 还款责任金额
                            PC02KJ01 = i.get("PC02KJ01")
                            if PC02KD02 not in null_type_list:
                                if PC02KD02 == "1":
                                    if floatCheck(PC02KJ02):
                                        factor.append(float(PC02KJ02))
                                    else:
                                        factor.append(None)
                                    if floatCheck(PC02KJ01):
                                        factor2.append(float(PC02KJ01))
                                    else:
                                        factor2.append(None)
                                else:
                                    factor.append(0)
                                    factor2.append(0)
                            else:
                                continue
                    else:
                        # 出现次数为[1.4],所以没有数据返回缺失
                        return u'缺失值'

    factor = [x for x in factor if x is not None]
    factor2 = [x for x in factor2 if x is not None]
    if len(factor2) == 0 or len(factor) == 0:
        return u'缺失值'
    else:
        try:
            if sum(factor2) == 0 or sum(factor) == 0:
                return 0
            else:
                return '%.4f' % (sum(factor) / sum(factor2))
        except:
            return u'缺失值'

if __name__ == '__main__':
    file_obj = open(r'../../data/IC/IC02_GuaranBalPro/IC.json', 'r')
    content = file_obj.read()
    IC_DSJ_2D = json.loads(content, strict=False)
    aa = guaranBalPro()
    print aa

result = guaranBalPro()
